//
//  AppDelegate.swift
//  Status
//
//  Created by 花轮 on 15/5/13.
//  Copyright (c) 2015年 花轮. All rights reserved.
//

import UIKit

var sharedUserAccount = UserAccount.loadUserAccount()

// 切换根视图控制器的通知
let LKSwitchRootViewControllerNotification = "LKSwitchRootViewControllerNotification"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.redColor()
        window?.makeKeyAndVisible()
        
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: LKSwitchRootViewControllerNotification, object: nil)
        
        showMainInterface()

        return true
    }
    
    // 所有根视图控制器的切换工作统一管理
    func switchRootViewController(n: NSNotification)
    {
        window!.rootViewController = UIStoryboard.initialViewController(n.object as! String)
    }
    
   
    // 主界面的流程
    func showMainInterface()
    {
        // 判断用户是否登录，如果没有登录，显示main
        var sbName = "Main"
        
        if sharedUserAccount != nil
        {
            sbName = isNewUpdate() ? "NewFeature" : "Welcome"
        }
        
        window!.rootViewController = UIStoryboard.initialViewController(sbName)
    }
    
    private func isNewUpdate() -> Bool
    {
        // 版本信息可以从MainBundle的Info.plist获取
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
//        println(currentVersion)
        
        let versionValue = NSNumberFormatter().numberFromString(currentVersion)!.doubleValue
        
        // 和沙盒中的进行比较
        let sanboxKey = "sanfboxKey"
        let defaults = NSUserDefaults.standardUserDefaults()
        let sandboxVersion = defaults.doubleForKey(sanboxKey)
        
        // 及时记录最新的版本
        defaults.setDouble(versionValue, forKey: sanboxKey)
        defaults.synchronize()
        
        return versionValue > sandboxVersion
    }
}

